//
//  CHBubbleMessageCell.m
//  ChildHoodStemp
//
//  Created by lixu on 13-10-5.
//
//

#import "CHBubbleMessageCell.h"
#import "UIImage+CHChatView.h"
#import "MicroDef.h"
#import "MutiltimediaView.h"
#import "Snsp.pb.h"
#import "UIUtil.h"
#import <QuartzCore/QuartzCore.h>
#import "CHImageScanView.h"
#import "ChatToolBar.h"
#import "UIButton+WebCache.h"
#import "ChildHoodService.h"
#import "ChildHoodMessage.h"
#import "CXmppRequestMgr.h"
#import "JKAlertDialog.h"
#import "NetAndAudioModel.h"
#import "MBProgressHUD+WZ.h"

@interface CHBubbleMessageCell ()<UIGestureRecognizerDelegate>

//@property (strong, nonatomic) CHBubbleView *bubbleView;
@property (strong, nonatomic) UILabel *timestampLabel;
@property (strong, nonatomic) UILabel *senderName;
@property (strong, nonatomic) UILabel *senderTitle;
@property (strong, nonatomic) UILabel *alertBottomTitle;
@property (assign, nonatomic) CHAvatarStyle avatarImageStyle;
@property (assign, nonatomic) CHBubbleMessageType type;
@property (assign, nonatomic) CHBubbleStyle style;
@property (assign, nonatomic) BOOL hasTimeLabel;
@property (retain, nonatomic) UILabel *voiceTime;
@property (retain, nonatomic) UIImageView *redPot;
@property (assign, nonatomic) MessageSendType sendType;


- (void)setup;
- (void)configureTimestampLabel;

- (void)configureWithType:(CHBubbleMessageType)type
              bubbleStyle:(CHBubbleStyle)bubbleStyle
              avatarStyle:(CHAvatarStyle)avatarStyle
                timestamp:(BOOL)hasTimestamp
                 isNotice:(BOOL)flag isHasSenderName:(BOOL)hasSenderName;

- (void)handleLongPress:(UILongPressGestureRecognizer *)longPress;
- (void)handleMenuWillHideNotification:(NSNotification *)notification;
- (void)handleMenuWillShowNotification:(NSNotification *)notification;

@end

@implementation CHBubbleMessageCell
@synthesize isNotice = _isNotice;
@synthesize bubbleView = _bubbleView;
@synthesize timestampLabel = _timestampLabel;
@synthesize messageList;

- (void)dealloc
{
//    NSLog(@"CHBubbleMessageCell dealloc");
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ProgressViewChangeValue" object:nil];
//    [[ChildHoodService defaultService] removeObserver:self forKeyPath:@"progressValue"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Initialization
- (id)initWithBubbleType:(CHBubbleMessageType)type
             bubbleStyle:(CHBubbleStyle)bubbleStyle
             avatarStyle:(CHAvatarStyle)avatarStyle
            hasTimestamp:(BOOL)hasTimestamp
                isNotice:(BOOL)flag isHasSenderName:(BOOL)hasSenderName reuseIdentifier:(NSString *)reuseIdentifier ismap:(BOOL)ismap
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if(self) {
        self.avatarImageStyle = avatarStyle;
        self.style = bubbleStyle;
        self.type = type;
        [self setup];
        [self configureWithType:type
                    bubbleStyle:bubbleStyle
                    avatarStyle:avatarStyle
                      timestamp:hasTimestamp
                       isNotice:flag isHasSenderName:hasSenderName];
        if (bubbleStyle == CHBubbleStylePicture) {
            if (ismap) {
                UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapBubbleViewTapEvent)];
                tap.numberOfTapsRequired = 1;
                tap.numberOfTouchesRequired = 1;
                [self.bubbleView addGestureRecognizer:tap];
            }
            else
            {
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pictureBubbleViewTapEvent:)];
            tap.numberOfTapsRequired = 1;
            tap.numberOfTouchesRequired = 1;
            [self.bubbleView addGestureRecognizer:tap];
            }
        } else if (bubbleStyle == CHBubbleStyleFile) {
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fileBubbleViewTapEvent)];
            tap.numberOfTapsRequired = 1;
            tap.numberOfTouchesRequired = 1;
            [self.bubbleView addGestureRecognizer:tap];

        } else if (bubbleStyle == CHBubbleStyleText) {
            UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongTextPress:)];
            recognizer.delegate = self;
            [recognizer setMinimumPressDuration:0.4];
            [self.bubbleView addGestureRecognizer:recognizer];

        } else if (bubbleStyle == CHBubbleStyleShke)
        {
            
        } else if (bubbleStyle == CHBubbleStyleVideo){
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoBubbleViewTapEvent)];
            tap.numberOfTapsRequired = 1;
            tap.numberOfTouchesRequired = 1;
            [self.bubbleView addGestureRecognizer:tap];
        } else if (bubbleStyle == CHBubbleStyleRedPacket){
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(redPacketBubbleViewTapEvent)];
            tap.numberOfTapsRequired = 1;
            tap.numberOfTouchesRequired = 1;
            [self.bubbleView addGestureRecognizer:tap];
        }

    }
    return self;
}
-(void)redPacketBubbleViewTapEvent
{
    if ([self.delegate respondsToSelector:@selector(openredPacketWithIndexPath:)]) {
        [self.delegate openredPacketWithIndexPath:self.cellIndexPath];
    }
}
- (void)fileBubbleViewTapEvent
{
    if ([self.delegate respondsToSelector:@selector(jumptoDownLoadFileWithIndexPath:)]) {
        [self.delegate jumptoDownLoadFileWithIndexPath:self.cellIndexPath];
    }
}

#pragma mark - Setup
- (void)setup
{
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.accessoryType = UITableViewCellAccessoryNone;
    self.accessoryView = nil;

    self.imageView.image = nil;
    self.imageView.hidden = YES;
    self.textLabel.text = nil;
    self.textLabel.hidden = YES;
    self.detailTextLabel.text = nil;
    self.detailTextLabel.hidden = YES;

}

- (void)handleLongText{
    if ([self.delegate respondsToSelector:@selector(touchCellCopyDeleteWithCell:)]) {
        [self.delegate touchCellCopyDeleteWithCell:self];
    }
}
- (void)handleLongReSender{
    if ([self.delegate respondsToSelector:@selector(touchCellReSenderWithCell:)]) {
        [self.delegate touchCellReSenderWithCell:self];
    }
}

- (void)handleLongOther{
    if ([self.delegate respondsToSelector:@selector(touchCellDeleteWithCell:)]) {
        [self.delegate touchCellDeleteWithCell:self];
    }
}

- (void)configureWithType:(CHBubbleMessageType)type
              bubbleStyle:(CHBubbleStyle)bubbleStyle
              avatarStyle:(CHAvatarStyle)avatarStyle
                timestamp:(BOOL)hasTimestamp
                 isNotice:(BOOL)flag isHasSenderName:(BOOL)hasSenderName
{
    CGFloat bubbleY = INSET_HEIGHT;
    CGFloat bubbleX = 0.0f;
    CGFloat originX = INSET_WIDTH;
    _hasTimeLabel = hasTimestamp;
    if(hasTimestamp) {
        [self configureTimestampLabel];
        bubbleY = TIMESTAMP_LABEL_HEIGHT + 3*INSET_HEIGHT;
    }
    
    bubbleX = kCHAvatarSize + 2*INSET_WIDTH;
    
    
    [self configureAvatarView];
    
    if (hasSenderName) {
       [self configureSenderNameLabel];
        _senderName.frame = CGRectMake(bubbleX, bubbleY, kCHAvatarSize, SENDERNAME_LABEL_HEIGHT);
        bubbleY = CGRectGetMaxY(_senderName.frame);
    }

    CGRect avatarRect = CGRectMake(originX, bubbleY, kCHAvatarSize, kCHAvatarSize);
    
    if (type == CHBubbleMessageTypeSended) {
        CGFloat x = HARDWARE_SCREEN_WIDTH - (kCHAvatarSize + INSET_WIDTH);
        avatarRect.origin.x = x;

    }
    _bubbleView = [[CHBubbleView alloc] initWithFrame:CGRectMake(bubbleX, bubbleY, 100, 40)
                                           bubbleType:type
                                          bubbleStyle:bubbleStyle
                                             isNotice:flag];
//    _senderTitle.frame = titleRect;
    _avatarView.frame = avatarRect;

    [self.contentView addSubview:_bubbleView];
    [self.contentView addSubview:_avatarView];

    
    
    if (type==CHBubbleMessageTypeSended&&(bubbleStyle==CHBubbleStylePicture||bubbleStyle==CHBubbleStyleVoice)) {
//        UILabel *lal = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _bubbleView.frame.size.width, _bubbleView.frame.size.height)];
//        lal.textAlignment = UITextAlignmentCenter;
//        lal.font = [UIFont systemFontOfSize:12];
//        lal.text = @"20%";
//        [_bubbleView addSubview:lal];
        
    }
    
//    [self.contentView sendSubviewToBack:_bubbleView];
}

- (void)configureAvatarView
{
    _avatarView = [UIButton buttonWithType:UIButtonTypeCustom];
    _avatarView.adjustsImageWhenHighlighted = NO;
    UILongPressGestureRecognizer *longPre = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(avatarViewDidLongPress:)];
    [longPre setMinimumPressDuration:0.4];
    longPre.delegate = self;
    [_avatarView addGestureRecognizer:longPre];
    
    _avatarView.backgroundColor = [UIColor clearColor];
    [_avatarView.layer setCornerRadius:6.0f];
    _avatarView.clipsToBounds = YES;
    [_avatarView addTarget:self action:@selector(jumpToDetailInfoView) forControlEvents:UIControlEventTouchUpInside];
}

- (void)jumpToDetailInfoView
{
    if ([self.delegate respondsToSelector:@selector(jumpToDetailInfoViewWithIndexPath:)]) {
        [self.delegate jumpToDetailInfoViewWithIndexPath:self.cellIndexPath];
    }
}
- (void)videoBubbleViewTapEvent
{
    
    if ([self.delegate respondsToSelector:@selector(openFullScreenPlayVido:)]) {
        [self.delegate openFullScreenPlayVido:self.cellIndexPath];
    }
}
- (void)configureSenderTitleLabel
{
    _senderTitle = [[UILabel alloc] init];
    _senderTitle.font = [UIFont systemFontOfSize:11.0f];
    _senderTitle.textColor = [UIColor lightGrayColor];
    _senderTitle.textAlignment = NSTextAlignmentCenter;
    _senderTitle.backgroundColor = [UIColor yellowColor];
    _senderTitle.hidden = YES;
    _senderTitle.text= @"hehehehe";
    _senderTitle.numberOfLines = 0;
}

- (void)configureSenderNameLabel
{
    _senderName = [[UILabel alloc] init];
    _senderName.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPre = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(senderNameDidLongPress:)];
    [longPre setMinimumPressDuration:0.4f];
    longPre.delegate = self;
    [_senderName addGestureRecognizer:longPre];
    
   
    _senderName.font = [UIFont systemFontOfSize:12.0f];
    _senderName.textColor = [UIColor grayColor];
    _senderName.textAlignment = NSTextAlignmentCenter;
    _senderName.backgroundColor = [UIColor clearColor];
    _senderName.numberOfLines = 1;
    [self.contentView addSubview:_senderName];
    [self.contentView bringSubviewToFront:_senderName];
}

- (void)configureTimestampLabel
{
    _timestampLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,self.bounds.size.width,TIMESTAMP_LABEL_HEIGHT)];
    _timestampLabel.center = CGPointMake(HARDWARE_SCREEN_WIDTH/2, TIMESTAMP_LABEL_HEIGHT/2);
//    _timestampLabel.autoresizingMask =  UIViewAutoresizingFlexibleWidth;
    _timestampLabel.backgroundColor = [UIUtil colorWithHexString:@"#000000" withAlpha:0.4f];
    _timestampLabel.layer.cornerRadius = 6.0f;
    _timestampLabel.clipsToBounds = YES;
    _timestampLabel.textAlignment = NSTextAlignmentCenter;
    _timestampLabel.textColor = [UIColor whiteColor];
    _timestampLabel.font = [UIFont boldSystemFontOfSize:11.5f];
    
    [self.contentView addSubview:_timestampLabel];
    [self.contentView bringSubviewToFront:_timestampLabel];
}

- (void)configureAlertTitleLabel
{
    _alertBottomTitle = [[UILabel alloc] initWithFrame:CGRectMake(0,0,self.bounds.size.width,14)];
    _alertBottomTitle.backgroundColor = RGBCOLOR(237, 237, 237);
    _alertBottomTitle.layer.cornerRadius = CGRectGetHeight(_alertBottomTitle.frame)/2;
    _alertBottomTitle.clipsToBounds = YES;
    _alertBottomTitle.textAlignment = NSTextAlignmentCenter;
    _alertBottomTitle.textColor = RGBCOLOR(135, 137, 8);
    _alertBottomTitle.font = [UIFont systemFontOfSize:13.0f];
    _alertBottomTitle.hidden = YES;
    _alertBottomTitle.backgroundColor = [UIColor redColor];
    [self.contentView addSubview:_alertBottomTitle];
    [self.contentView bringSubviewToFront:_alertBottomTitle];
}

- (void)didtap
{
    
}

- (void)avatarViewDidLongPress:(UILongPressGestureRecognizer *)longPress
{
    if (M_ISSTRNULL(self.chidMessage.GroupId)) {
        return;
    }
    if(longPress.state != UIGestureRecognizerStateBegan || ![self becomeFirstResponder])
        return;

    ChatToolBar *tool = [ChatToolBar defaultChatToolBar];
    if (!tool.contentText.internalTextView.text) {
        tool.contentText.internalTextView.text = @"";
    }
    
    NSRange tempRange = [tool.contentText.internalTextView selectedRange];
    if (tool.textSelectRange.location<[tool.contentText.internalTextView selectedRange].location && tool.textSelectRange.location!=0) {
        tempRange = tool.textSelectRange;
    }
    
    NSString *firstStr = [tool.contentText.internalTextView.text substringToIndex:tempRange.location];
    NSString *lastStr =[tool.contentText.internalTextView.text substringFromIndex:tempRange.location];
    NSString *str = [NSString stringWithFormat:@"@%@ ",self.chidMessage.fromName];
    NSString *new_str = [NSString stringWithFormat:@"%@%@%@",firstStr,str,lastStr];
    NSRange range = NSMakeRange([[NSString stringWithFormat:@"%@%@",firstStr,str] length], 1);
    tool.textSelectRange = range;
    [tool.contentText setText:new_str];

}

- (void)senderNameDidLongPress:(UILongPressGestureRecognizer *)longPress
{
    if(longPress.state != UIGestureRecognizerStateBegan || ![self becomeFirstResponder])
        return;

    ChatToolBar *tool = [ChatToolBar defaultChatToolBar];
    if (!tool.contentText.internalTextView.text) {
        tool.contentText.internalTextView.text = @"";
    }
    
    NSRange tempRange = [tool.contentText.internalTextView selectedRange];
    if (tool.textSelectRange.location<[tool.contentText.internalTextView selectedRange].location && tool.textSelectRange.location!=0) {
        tempRange = tool.textSelectRange;
    }
    
    NSString *firstStr = [tool.contentText.internalTextView.text substringToIndex:tempRange.location];
    NSString *lastStr =[tool.contentText.internalTextView.text substringFromIndex:tempRange.location];
    NSString *str = [NSString stringWithFormat:@"@%@ ",self.chidMessage.fromName];
    
    NSString *new_str = [NSString stringWithFormat:@"%@%@%@",firstStr,str,lastStr];
    NSRange range = NSMakeRange([[NSString stringWithFormat:@"%@%@",firstStr,str] length], 1);
    tool.textSelectRange = range;
    
     [tool.contentText setText:new_str];
    

}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setActivityIndicatorStatus:(int32_t)status andProcess:(NSInteger)process
{
    self.sendType = status;
    
    if (self.style == CHBubbleStyleText || self.style == CHBubbleStyleVoice) {
        
        UIView *statusView = [self viewWithTag:144444];
        if (statusView) {
                [statusView removeFromSuperview];
                statusView = nil;
        }

        
        switch (status) {
            case kMessageSending:
            {
                UIView *statusView = [self viewWithTag:98765];
                if (statusView) {
                    if (![statusView isKindOfClass:[UIActivityIndicatorView class]])
                    {
                        [statusView removeFromSuperview];
                        statusView = nil;
                    }
                }
                if (statusView==nil)
                {
                    statusView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                    [statusView setFrame:CGRectMake(0, 0, 20, 20)];
                    statusView.tag = 98765;
                    [statusView setHidden:NO];
                    [self.contentView addSubview:statusView];
                }
                [statusView setFrame:CGRectMake(self.bubbleView.frame.origin.x+self.bubbleView.frame.size.width,
                                                15,
                                                statusView.frame.size.width,
                                                statusView.frame.size.height)];
                if (self.type == CHBubbleMessageTypeSended)
                {
                    [statusView setFrame:CGRectMake(self.bubbleView.frame.origin.x-statusView.frame.size.width,
                                                    15+(_hasTimeLabel?TIMESTAMP_LABEL_HEIGHT:0),
                                                    statusView.frame.size.width,
                                                    statusView.frame.size.height)];
                } else {
                    [statusView setFrame:CGRectMake(CGRectGetMaxX(self.bubbleView.frame) + 5.0f,
                                                    15+(_hasTimeLabel?TIMESTAMP_LABEL_HEIGHT:0),
                                                    statusView.frame.size.width,
                                                    statusView.frame.size.height)];

                }
                CGPoint cer = statusView.center;
                cer.y = self.bubbleView.center.y;
                statusView.center = cer;

                [(UIActivityIndicatorView *)statusView startAnimating];
                break;
            }
            case kMessageOK:
            {
                
                UIView *statusView = [self viewWithTag:98765];
                if (statusView) {
                    [statusView removeFromSuperview];
                }
                break;
            }
            case kMessageSendFailed:
            {
                UIView *statusView = [self viewWithTag:98765];
                if (statusView) {
                    if (![statusView isKindOfClass:[UIButton class]])
                    {
                        [statusView removeFromSuperview];
                        statusView = nil;
                    }
                }
                if (statusView==nil) {
                    statusView = [UIButton buttonWithType:UIButtonTypeCustom];
                    [(UIButton *)statusView setImage:[UIImage imageNamed:@"loginErrorImage"] forState:UIControlStateNormal];
                    statusView.tag = 98765;
                    statusView.frame = CGRectMake(0, 0, 20, 20);
                    [(UIButton *)statusView addTarget:self action:@selector(reSendMessage:) forControlEvents:UIControlEventTouchUpInside];
                    
                    [self.contentView addSubview:statusView];
                }
                [statusView setFrame:CGRectMake(self.bubbleView.frame.origin.x+self.bubbleView.frame.size.width,
                                                15,
                                                statusView.frame.size.width,
                                                statusView.frame.size.height)];
                if (self.type == CHBubbleMessageTypeSended)
                {
                    [statusView setFrame:CGRectMake(self.bubbleView.frame.origin.x-statusView.frame.size.width,
                                                    15+(_hasTimeLabel?TIMESTAMP_LABEL_HEIGHT:0),
                                                    statusView.frame.size.width,
                                                    statusView.frame.size.height)];
                }
                CGPoint cer = statusView.center;
                cer.y = self.bubbleView.center.y;
                statusView.center = cer;
                break;
            }
            default:
                break;
        }
    } else {
        
        switch (status) {
            case kMessageSending:
            {
                __block NetAndAudioModel *netAndAudio = nil;
                [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
                    if ([self.chidMessage.fileName isEqualToString:obj.serFileName]) {
                        netAndAudio = obj;
                        *stop = YES;
                    }
                }];

                UIView *statusView = [self viewWithTag:98765];
                if (statusView) {
                    [statusView removeFromSuperview];
                    statusView = nil;
                }
                UIView *progressView = [self viewWithTag:144444];
                if (progressView == nil) {
                    progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
                    progressView.tag = 144444;
                    [progressView setFrame:CGRectMake(self.bubbleView.frame.origin.x,
                                                      CGRectGetMaxY(self.bubbleView.frame) + 5,
                                                      self.bubbleView.frame.size.width,
                                                      10)];
                    progressView.tintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
                    progressView.backgroundColor = BlackColor;
                    progressView.transform = CGAffineTransformMakeScale(1.0f,3.0f);
                    [self.contentView addSubview:progressView];
                    self.progressView = (UIProgressView *)progressView;
                    if (netAndAudio) {
                        self.progressView.progress = netAndAudio.progresValue;
                        __weak typeof (self) weakself = self;
                        [netAndAudio.manager setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                CGFloat value = totalBytesSent / (float)totalBytesExpectedToSend;
    
                                weakself.progressView.progress = value;
                                //bug 8537 fixed by lixu
                                if (weakself.progressView.progress == 1) {
                                    [weakself.progressView removeFromSuperview];
                                }
                        });
                        }];

                    }
                    
                }
 
            }
                break;
            case kMessageOK:{
//                [[ChildHoodService defaultService] removeObserver:self forKeyPath:@"progressValue"];
                UIView *statusView = [self viewWithTag:98765];
                if (statusView) {
                    [statusView removeFromSuperview];
                    statusView = nil;
                }
                
                UIView *progressView = [self viewWithTag:144444];
                if (progressView) {
                    [progressView removeFromSuperview];
                    progressView = nil;
                }

                break;
                
            }
                break;
            case kMessageSendFailed:{
                
                UIView *progressView = [self viewWithTag:144444];
                if (progressView) {
                    [progressView removeFromSuperview];
                    progressView = nil;
                }
                
                UIView *statusView = [self viewWithTag:98765];
                if (statusView) {
                    if (![statusView isKindOfClass:[UIButton class]])
                    {
                        [statusView removeFromSuperview];
                        statusView = nil;
                    }
                }
                if (statusView==nil) {
                    statusView = [UIButton buttonWithType:UIButtonTypeCustom];
                     [(UIButton *)statusView setImage:[UIImage imageNamed:@"loginErrorImage"] forState:UIControlStateNormal];
                    statusView.tag = 98765;
                    statusView.frame = CGRectMake(0, 0, 20, 20);
                    [(UIButton *)statusView addTarget:self action:@selector(reSendMessage:) forControlEvents:UIControlEventTouchUpInside];
                    [self.contentView addSubview:statusView];
                }
                [statusView setFrame:CGRectMake(self.bubbleView.frame.origin.x+self.bubbleView.frame.size.width,
                                                15,
                                                statusView.frame.size.width,
                                                statusView.frame.size.height)];
                if (self.type == CHBubbleMessageTypeSended)
                {
                    [statusView setFrame:CGRectMake(self.bubbleView.frame.origin.x-statusView.frame.size.width,
                                                    15+(_hasTimeLabel?TIMESTAMP_LABEL_HEIGHT:0),
                                                    statusView.frame.size.width,
                                                    statusView.frame.size.height)];
                }
                CGPoint cer = statusView.center;
                cer.y = self.bubbleView.center.y;
                statusView.center = cer;

            }
            
                break;
            default:
                break;
        }
        
    }
}

-(void)reSendMessage:(UIButton *)button
{
    if (![[CXmppMgr shareInstance].xmppStream isAuthenticated]) {
        [MBProgressHUD showError:@"网络不可用，请您检查网络!"];
        return;
    }
    [[ChatToolBar defaultChatToolBar] reSetChatTool];
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"您确定要重新发送吗？"];
    [alert addButton:Button_OK withTitle:@"重新发送" handler:^(JKAlertDialogItem *item) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RESENDMESSAGE" object:self.chidMessage];
        
    }];
    
    [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
        
    }];
    [alert show];

    
}
-(void)mapBubbleViewTapEvent
{
    if ([self.delegate respondsToSelector:@selector(jumptoMapWithIndexPath:)]) {
        [self.delegate jumptoMapWithIndexPath:self.cellIndexPath];
    }
}
-(void)pictureBubbleViewTapEvent:(id)sender
{
//    yh bug 6535
    [[ChatToolBar defaultChatToolBar] reSetChatTool];
    CHImageScanView *scan = [CHImageScanView sharedInstance];
    scan.imageArray = nil;
    scan.chMessages = self.messageList;
    
    [scan showImgWithIndexPath:self.cellIndexPath];
    if(self.largePicURI != nil)
    {
    }
}

- (void)hideRedpot
{
    _redPot.hidden = YES;
}

#pragma mark - Setters
- (void)setBackgroundColor:(UIColor *)color
{
    [super setBackgroundColor:color];
    [self.contentView setBackgroundColor:color];
    [self.bubbleView setBackgroundColor:color];
}

#pragma mark - Message Cell
- (void)setPicture:(NSString *)uri nextURI:(NSString *)nextUri withStatus:(int32_t)status andProcess:(NSInteger)process fileName:(NSString *)fileName fileId:(NSString *)fileId chatType:(NSString *)chatType childMessage:(ChildHoodMessage *)message
{
    for (UIView *aView in [self.bubbleView.pictureView subviews]) {
        [aView removeFromSuperview];
    }
    self.largePicURI = nextUri;
    [self.bubbleView.pictureView setDownloadUrlWithFileName:fileName fileId:fileId chatType:chatType childMessage:message];
//    [self.bubbleView.pictureView setMultimediaFileUri:uri type:SNSPMaterialTypeKImage];
    [self setActivityIndicatorStatus:status andProcess:process];
}
-(void)setVideo:(NSString *)url withStatus:(int32_t)status andProcess:(NSInteger)process fileName:(NSString *)fileName fileId:(NSString *)fileId chatType:(NSString *)chatType chileMessage:(ChildHoodMessage *)message
{
    for (UIView *aView in [self.bubbleView.videoView subviews]) {
        [aView removeFromSuperview];
    }
    [self.bubbleView.videoView setDownloadUrlWithFileName:fileName fileId:fileId chatType:chatType childMessage:message];
    //    [self.bubbleView.pictureView setMultimediaFileUri:uri type:SNSPMaterialTypeKImage];
    [self setActivityIndicatorStatus:status andProcess:process];
}
- (void)setFileWithStatus:(int32_t)status andProcess:(NSInteger)process fileName:(NSString *)fileName fileId:(NSString *)fileId chatType:(NSString *)chatType childMessage:(ChildHoodMessage *)message
{
    for (UIView *aView in [self.bubbleView.fileView subviews]) {
        [aView removeFromSuperview];
    }
    [self.bubbleView.fileView setDownloadUrlWithFileName:fileName fileId:fileId chatType:chatType childMessage:message];
//    [self.bubbleView.fileView setMultimediaFileUri:fileName type:SNSPMaterialTypeKFile];
    [self setActivityIndicatorStatus:status andProcess:process];

}

- (void)setVoice:(NSString *)uri totalTime:(CGFloat)time isRead:(MessageSoundPlayStatus)flag withStatus:(int32_t)status andProcess:(NSInteger)process fileName:(NSString *)fileName fileId:(NSString *)fileId chatType:(NSString *)chatType childMessage:(ChildHoodMessage *)message
{
    CGFloat times = ceilf(time);
    if(times < 1){
        times = 1;
        time = 1;
    }
    if (times >= 1 && times <= 16) {
        CGFloat tmp = times-2;
        [self.bubbleView setBubbleFrameWithSize:CGSizeMake(70+tmp*5, 47)];
    }
    else if (times > 16)
    {
        [self.bubbleView setBubbleFrameWithSize:CGSizeMake(140, 47)];
    }
    
    [self.bubbleView.voiceView setDownloadUrlWithFileName:fileName fileId:fileId chatType:chatType childMessage:message];
//    [self.bubbleView.voiceView setMultimediaFileUri:uri type:SNSPMaterialTypeKAudio];
//    [self.bubbleView.voiceView setVoiceLenth:(NSInteger)time];
//    self.bubbleView.voiceView.is_played = flag;
    [self setActivityIndicatorStatus:status andProcess:process];
    if (status == kMessageOK) {
        if (!_redPot) {
            _redPot = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"voice_redpot.png"]];
            [self addSubview:_redPot];
        }
        CGFloat redpotPosX = (self.type == CHBubbleMessageTypeSended)?(self.bubbleView.frame.origin.x-13):(self.bubbleView.frame.origin.x+self.bubbleView.frame.size.width+5);
        CGRect redpotRect = CGRectMake(redpotPosX,
                                 INSET_HEIGHT+(_hasTimeLabel?TIMESTAMP_LABEL_HEIGHT+2*INSET_HEIGHT+8:8),
                                 10,
                                 10);
        _redPot.frame = redpotRect;
        CGPoint cer = _redPot.center;
        cer.y = self.bubbleView.center.y;
        _redPot.center = cer;
        if (flag != MessageSoundNotPlay) {
            _redPot.hidden = YES;
//            NSLog(@"yes");
        }
        else
        {
            _redPot.hidden = NO;
//            NSLog(@"no");
        }
//        if (!_voiceTime) {
//            _voiceTime = [[UILabel alloc] init];
//            _voiceTime.font = Font14;
//            _voiceTime.textColor = ContentDarkGrayColor;
//            _voiceTime.textAlignment = NSTextAlignmentCenter;
//            _voiceTime.backgroundColor = [UIColor clearColor];
//            [self addSubview:_voiceTime];
//        }
//        CGFloat voiceTimePosX = (self.type == CHBubbleMessageTypeSended)?(self.bubbleView.frame.origin.x-25):(self.bubbleView.frame.origin.x+self.bubbleView.frame.size.width);
//        CGRect rect = CGRectMake(voiceTimePosX,
//                                 30+(_hasTimeLabel?TIMESTAMP_LABEL_HEIGHT+2*INSET_HEIGHT:0),
//                                 25,
//                                 16);
//        _voiceTime.frame = rect;
//        _voiceTime.text = [NSString stringWithFormat:@"%.f\"",times];
//        _voiceTime.hidden = NO;
    }
    else
    {
        _voiceTime.hidden = YES;
        _redPot.hidden = YES;
    }
}
-(void)setRedPacketInfo:(NSString *)info withStatus:(int32_t)status
{
    [self.bubbleView.redpacketView setRedpacketInfo:info];
    [self setActivityIndicatorStatus:status andProcess:-1];
}
- (void)setMessage:(NSString *)msg withStatus:(int32_t) status
{
    self.bubbleView.text = msg;
    
    [self setActivityIndicatorStatus:status andProcess:-1];
}

- (void)setTimestamp:(NSDate *)date
{
    NSString *str = [UIUtil timeForMessageStyle:date];
    CGSize size = [str sizeWithFont:[UIFont boldSystemFontOfSize:11.5f]];
    CGRect frame = _timestampLabel.frame;
    _timestampLabel.frame = CGRectMake(frame.origin.x, frame.origin.y, size.width+10, TIMESTAMP_LABEL_HEIGHT);
    _timestampLabel.center = CGPointMake(HARDWARE_SCREEN_WIDTH/2, TIMESTAMP_LABEL_HEIGHT/2);
    _timestampLabel.text = str;
}

- (void)setName:(NSString *)senderName
{
    
    self.senderName.text = senderName;//[NSString stringWithFormat:@"%@adfafdadaadfd",senderName];
}

- (void)setTitle:(NSString *)senderTitle
{
    self.senderTitle.text = @"jfdajfdlajdfla";
}

- (void)setAvatarImage:(NSString *)uri
{
    if ([self.chidMessage.MineUserId isEqualToString:self.chidMessage.FriendUserId]) {
        if (self.chidMessage.isMine == CHBubbleMessageTypeSended) {
            [_avatarView setBackgroundImage:[UIImage imageNamed:@"icon-iPhone_chat"] forState:UIControlStateNormal];
        } else {
            [_avatarView setBackgroundImage:[UIImage imageNamed:@"icon-iMAC_chat"] forState:UIControlStateNormal];
        }
    } else {
        if (self.chidMessage.isMine != CHBubbleMessageTypeSended && self.chidMessage.isKefu) {
            [_avatarView setBackgroundImage:[UIImage imageNamed:@"head-kefu"] forState:UIControlStateNormal];
        } else {
            [_avatarView sd_setBackgroundImageWithURL:[NSURL URLWithString:uri] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"90-90"]];
 
        }
    }
    //    MutiltimediaView *aView = (MutiltimediaView *)[_avatarView viewWithTag:3452345];
//    if (aView == nil) {
//        aView = [[MutiltimediaView alloc] initWithFrame:CGRectMake(0, 0, _avatarView.frame.size.width, _avatarView.frame.size.height)];
//        aView.tag = 3452345;
//        aView.userInteractionEnabled = NO;
//        [_avatarView addSubview:aView];
//        [aView setMultimediaFileUri:uri type:SNSPMaterialTypeKImage];
//    }
//    else
//    {
//        [aView setMultimediaFileUri:uri type:SNSPMaterialTypeKImage];
//    }
}

- (void)setIndexPathForVoice
{
    self.bubbleView.voiceView.indexPath = _cellIndexPath;
}

- (void)setMemoryID:(uint32_t)memoryID
{
    self.avatarView.tag = memoryID;
}

- (void)setMessageStatus:(MessageSendType)type
{
    if(type == kMessageUserMute)
    {
        _alertBottomTitle.hidden = NO;
        NSString *str = @"您的群聊功能暂不可用,请联系本班老师帮助处理.";
        CGSize size = [str sizeWithFont:_alertBottomTitle.font];
        
        _alertBottomTitle.frame = CGRectMake(0, 0, size.width+10, size.height);
        float marginY = CGRectGetMaxY(_senderTitle.frame);
        if (marginY < CGRectGetMaxY(_bubbleView.frame)) {
            marginY =  CGRectGetMaxY(_bubbleView.frame);
        }
        _alertBottomTitle.center = CGPointMake(HARDWARE_SCREEN_WIDTH/2, marginY + SendAlert_Label_Height -  size.height/2);
        _alertBottomTitle.text = str;
    }
    else
    {
        _alertBottomTitle.hidden = YES;
    }
}

+ (CGFloat)neededHeightForText:(NSString *)bubbleViewText timestamp:(BOOL)hasTimestamp isHasSenderName:(BOOL)hasSenderName
{
    CGFloat timestampHeight = (hasTimestamp) ? (TIMESTAMP_LABEL_HEIGHT + 2*INSET_HEIGHT) : 0.0f;
    CGFloat hasSenderNameHeight = hasSenderName ? SENDERNAME_LABEL_HEIGHT : 0.0f;
    CGFloat cellheight1 = timestampHeight + hasSenderNameHeight + INSET_HEIGHT + kCHAvatarSize + INSET_HEIGHT + SENDERNAME_LABEL_HEIGHT + SENDERTITLE_LABEL_HEIGHT + INSET_HEIGHT;
    CGFloat cellheight2 = timestampHeight + hasSenderNameHeight + INSET_HEIGHT + [CHBubbleView cellHeightForText:bubbleViewText] + INSET_HEIGHT;
    
    return MAX(cellheight1, cellheight2);
}

#pragma mark - Copying
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)becomeFirstResponder
{
    return [super becomeFirstResponder];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    [super canPerformAction:action withSender:sender];
    if(action == @selector(copy:)||action == @selector(forWard:))
        return YES;
//    if (action==@selector(delete:)) {
//        return YES;
//    }
    return NO;
}
-(void)forWard:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(menuControllerDidForWardWithString:)]) {
        [self.delegate menuControllerDidForWardWithString:self.bubbleView.text];
    }
    [self resignFirstResponder];
}
- (void)delete:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(menuControllerDidDeleteWithIndexpath:)]) {
        [self.delegate menuControllerDidDeleteWithIndexpath:self.cellIndexPath];
    }
}

- (void)copy:(id)sender
{
    [[UIPasteboard generalPasteboard] setString:self.bubbleView.text];
    [self resignFirstResponder];
}

#pragma mark - Touch events
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    if(![self isFirstResponder])
        return;
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setMenuVisible:NO animated:YES];
    [menu update];
    [self resignFirstResponder];
}

#pragma mark - Gestures
- (void)handleLongPress:(UILongPressGestureRecognizer *)longPress
{
    if(longPress.state != UIGestureRecognizerStateBegan || ![self becomeFirstResponder])
        return;
//    [[ChatToolBar defaultChatToolBar] reSetChatTool];
//    UIMenuController *menu = [UIMenuController sharedMenuController];
//    CGRect targetRect = [self convertRect:[self.bubbleView SOLO555YANGbubbleFrame]
//                                 fromView:self.bubbleView];
//    [menu setTargetRect:CGRectInset(targetRect, 0.0f, 4.0f) inView:self];
//    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMenuWillShowNotification:)
                                                 name:UIMenuControllerWillShowMenuNotification
                                               object:nil];
//    [menu setMenuVisible:YES animated:YES];
}

- (void)handleLongTextPress:(UILongPressGestureRecognizer *)longPress{
    if(longPress.state != UIGestureRecognizerStateBegan || ![self becomeFirstResponder])
        return;
        UIMenuController *menu = [UIMenuController sharedMenuController];
        UIMenuItem *forwardItem = [[UIMenuItem alloc] initWithTitle:@"转发"action:@selector(forWard:)];
       [menu setMenuItems:@[forwardItem]];
        CGRect targetRect = [self convertRect:[self.bubbleView bubbleFrame]
                                     fromView:self.bubbleView];
        [menu setTargetRect:CGRectInset(targetRect, 0.0f, 4.0f) inView:self];
        [menu setMenuVisible:YES animated:YES];
//    [self handleLongText];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMenuWillShowNotification:)
                                                 name:UIMenuControllerWillShowMenuNotification
                                               object:nil];
}
- (void)handleLongOtherPress:(UILongPressGestureRecognizer *)longPress{
    if(longPress.state != UIGestureRecognizerStateBegan || ![self becomeFirstResponder])
        return;
    //    [[ChatToolBar defaultChatToolBar] reSetChatTool];
        UIMenuController *menu = [UIMenuController sharedMenuController];
    UIMenuItem *checkItem = [[UIMenuItem alloc] initWithTitle:@"查看"action:@selector(forWard:)];
    [menu setMenuItems:@[checkItem]];
        CGRect targetRect = [self convertRect:[self.bubbleView bubbleFrame]
                                     fromView:self.bubbleView];
        [menu setTargetRect:CGRectInset(targetRect, 0.0f, 4.0f) inView:self];
    
        [menu setMenuVisible:YES animated:YES];
//    [self handleLongOther];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMenuWillShowNotification:)
                                                 name:UIMenuControllerWillShowMenuNotification
                                               object:nil];
}

-(void)handleLongReSenderPress:(UILongPressGestureRecognizer *)longPress{
    if(longPress.state != UIGestureRecognizerStateBegan || ![self becomeFirstResponder])
        return;
//    [self handleLongReSender];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMenuWillShowNotification:)
                                                 name:UIMenuControllerWillShowMenuNotification
                                               object:nil];
}


#pragma mark - Notification
- (void)handleMenuWillHideNotification:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIMenuControllerWillHideMenuNotification
                                                  object:nil];
    self.bubbleView.selectedToShowCopyMenu = NO;
}

- (void)handleMenuWillShowNotification:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIMenuControllerWillShowMenuNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMenuWillHideNotification:)
                                                 name:UIMenuControllerWillHideMenuNotification
                                               object:nil];
    
    self.bubbleView.selectedToShowCopyMenu = YES;
}


@end
